package com.uestc.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class PackUtil {
    public static void packFile(List<File> sourceFiles, String targetPath) {
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(targetPath))) {
            dos.writeInt(sourceFiles.size());
            for (File file : sourceFiles) {
                String fileName = file.getName();
                dos.writeInt(fileName.length());
                dos.writeChars(fileName);

                byte[] bytes = Files.readAllBytes(Paths.get(file.getPath()));
                dos.writeInt(bytes.length);
                dos.write(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void restoreFile(List<File> sourceFiles, String targetPath) {
        for (File file : sourceFiles) {
            try (DataInputStream dis = new DataInputStream(new FileInputStream(file.getPath()))) {
                int fileNum = dis.readInt();
                for (int i = 0; i < fileNum; i++) {
                    int fileNameLength = dis.readInt();
                    StringBuilder fileName = new StringBuilder();
                    for (int j = 0; j < fileNameLength; j++) {
                        fileName.append(dis.readChar());
                    }

                    int len = dis.readInt();
                    byte[] bytes = new byte[len];
                    dis.readFully(bytes);
                    Files.write(Paths.get(targetPath + "\\" + fileName), bytes);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
